<?php

jimport('joomla.application.component.view');
class WrdViewRedemption extends WrdView{
	
    function display($tpl = null)
    {
        $fnc = 'display' . ucfirst($this->getLayout());
        if (is_callable(array(
            &$this,
            $fnc
        ))) {
            $this->$fnc($tpl);
        } else {
            parent::display($tpl);
        }
    }
    
    function displayDefault($tpl = null){
    	
        $mainframe =& JFactory::getApplication();
        $user   = JFactory::getUser();
        $cat_id = JRequest::getInt('cid');
        $p_id   = JRequest::getInt('pid');
        
        if ($user->id != 0) {
            $model_profile = $this->getModel('profile');
            $user_info     = $model_profile->getUserProfile($user->id);
            if (!empty($cat_id) && $cat_id != 0 && !empty($p_id) && $p_id != 0) {
                //Lay chi tiet san pham co category id va product id da lay duoc                
                $model_product   = $this->getModel('products');
                $category        = $model_product->getNameCat($cat_id);
                $product_details = $model_product->getProductsDetails($cat_id, $p_id);
                $list_image      = array();
                $list_image      = $model_product->getListImages($product_details->id, 0);
            } //page title and point of user
               
            $p_o_u = WrdHelper::getPoints($user->id);
           
            $this->assignRef('p_o_u', $p_o_u);
            $p_title = WrdHelper::getPageTitle();
            $this->assignRef('p_title', $p_title);
            $this->assignRef('user_info', $user_info);
            $this->assignRef('user', $user);
            $this->assignRef('product_details', $product_details);
            $this->assignRef('list_image', $list_image);
            
        } else {
            $user_info = null;
            $mainframe->redirect(WrdHelperRoute::getProfileLoginRoute(), 'You must login first');
        }
        parent::display($tpl);
    }
    
    function displayProducts($tpl = null)
    {
        $mainframe =& JFactory::getApplication();
        $user          = JFactory::getUser();
        $cat_id        = JRequest::getInt('cid');
        $limit_start   = JRequest::getInt('limitstart', 0);
        $limit         = JRequest::getInt('limit', 9);
        $model_profile = $this->getModel('profile');
        $user_info     = $model_profile->getUserProfile($user->id);
        
        if (!empty($cat_id) && $cat_id != 0) { //Lay danh sach cac san pham theo category da lay duoc           
            $model_product = $this->getModel('products');
            $category      = $model_product->getNameCat($cat_id);
            $list_product  = $model_product->getListProductsByCatId($cat_id, $limit_start, $limit, 0, 0);
            $list_image    = array();
            foreach ($list_product as $product) {
                $list_image[$product->id] = $model_product->getListImages($product->id, 1);
            }
            $total      = $model_product->getListProductsByCatId($cat_id, '', '', 1, 0);
            $pagination = $model_product->getPaging($total, $limit_start, $limit);
        }
        
        $this->assignRef('user_info', $user_info);
        $this->assignRef('user', $user);
        $this->assignRef('list_products', $list_product);
        $this->assignRef('list_image', $list_image);
        $this->assignRef('cat_name', $category->cat_name);
        $this->assignRef('pagination', $pagination); //page title and point of user        
        $p_o_u = WrdHelper::getPoints($user->id); 
        $this->assignRef('p_o_u', $p_o_u);
        $p_title = WrdHelper::getPageTitle();
        $this->assignRef('p_title', $p_title);
        parent::display($tpl);
    }
    
    function displayProduct($tpl = null)
    {
        $mainframe =& JFactory::getApplication();
        $user          = JFactory::getUser();
        $limit_start   = JRequest::getInt('limitstart', 0);
        $limit         = JRequest::getInt('limit', 9);
        $cat_id        = JRequest::getInt('cid');
        $p_id          = JRequest::getInt('pid');
        $model_profile = $this->getModel('profile');
        $user_info     = $model_profile->getUserProfile($user->id);
        
        if (!empty($cat_id) && $cat_id != 0 && !empty($p_id) && $p_id != 0) { //Lay chi tiet san pham co category id va product id da lay duoc            
            $model_product          = $this->getModel('products');
            $category               = $model_product->getNameCat($cat_id);
            $product_details        = $model_product->getProductsDetails($cat_id, $p_id);
            $list_image             = array();
            $list_image             = $model_product->getListImages($product_details->id, 0); //Get products same category            
            $list_products_same_cat = $model_product->getListProductsByCatId($cat_id, $limit_start, $limit, 0, $p_id);
            $list_image_same        = array();
            foreach ($list_products_same_cat as $product)
                $list_image_same[$product->id] = $model_product->getListImages($product->id, 1);
            $total      = $model_product->getListProductsByCatId($cat_id, '', '', 1, $p_id);
            $pagination = $model_product->getPaging($total, $limit_start, $limit);
        } //page title and point of user      
          
        $p_o_u = WrdHelper::getPoints($user->id);        
        $this->assignRef('p_o_u', $p_o_u);
        $p_title = WrdHelper::getPageTitle();
        $this->assignRef('p_title', $p_title);
        $this->assignRef('user_info', $user_info);
        $this->assignRef('user', $user);
        $this->assignRef('product_details', $product_details);
        $this->assignRef('list_image', $list_image); //show list of product same category        
        $this->assignRef('list_products_same_cat', $list_products_same_cat);
        $this->assignRef('list_image_same', $list_image_same);
        $this->assignRef('cat_name', $category->cat_name);
        $this->assignRef('pagination', $pagination);
        parent::display($tpl);
    }
    
    function displayProcess($tpl = null)
    {
        $mainframe =& JFactory::getApplication();
        $user = JFactory::getUser();
        if ($user->id != 0) { // get products from parameter            
            $products = $_GET['product']; // get products from session;            
            if ($_SESSION['form_convert'] != null) {
                $products = array_merge($_SESSION['form_convert'], $products);
            } // save session            
            $_SESSION['form_convert'] = $products;
            $mainframe->redirect('index.php?option=com_wrd&view=redemption&layout=confirm');
        }
    }
    
    function displayRedeem($tpl = null)
    {
        $mainframe = JFactory::getApplication();
        $post      = JRequest::get($post);
        $db        = JFactory::getDbo();
        $vercode   = self::random_letters();
        
        $mainframe->setUserState("confirm_number", $vercode);
        $mainframe->setUserState("flag_here", "$vercode"); //get user        
        
        $user          = JFactory::getUser();
        $model_profile = $this->getModel('profile');
        $user_info     = $model_profile->getUserProfile($user->id);
        $outlet        = $_GET['res'];
        
        $query         = 'UPDATE #__wrd_profile SET pick_up_at = ' . $outlet . ' WHERE user_id = ' . $user_info->id;
        $db->setQuery($query);
        $db->query(); //get product        
        $query = 'SELECT * FROM #__wrd_products WHERE id = ' . $post['pid'];
        
        $db->setQuery($query);
        $rs            = $db->loadObject(); //get point detail        
        $point         = WrdHelper::getPoints($user->id);
        $products      = $_SESSION['form_convert'];
        $model_product = $this->getModel('products');
        
        foreach ($products as $product) {
            $props = explode(";", $product);
            if ($props['2'] != '0') {
                $method         = $props['0'];
                $product_detail = $model_product->getProductsConfirm($props['1']);
                $qty            = $props['2'];
            }
            $point_redeem = 0;
            $cash_redeem  = 0;
            if ($props['0'] == 'p') {
                $t_point      = $product_detail->point;
                $t_cash       = 0;
                $point_redeem = $qty * $t_point;
            } else {
                $t_point      = $product_detail->pointx;
                $t_cash       = $product_detail->cash;
                $point_redeem = $qty * $t_point;
                $cash_redeem  = $qty * $t_cash;
            }
            if ($point >= $point_redeem) { //updated point                
                $obj               = new stdClass();
                $obj->id           = null;
                $obj->user_id      = $user->id;
                $obj->transaction  = $rs->id;
                $obj->type         = 0;
                $obj->point        = -$point_redeem;
                $obj->expire       = '0000-00-00 00:00:00';
                $obj->point        = -$point_redeem;
                $obj->des          = 'Redemption';
                $obj->created_id   = $user->id;
                $obj->created_date = date('Y-m-d');
                $obj->modify_id    = '0';
                $obj->modify_date  = '0000-00-00 00:00:00';
				$obj->flagConvert  = 1;
                $db->insertObject('#__wrd_point', $obj);
                unset($obj);
                
                $temp                           = $db->insertid(); //process gift                
                $obj                            = new stdClass();
                $obj->id                        = null;
                $obj->user_id                   = $user->id;
                $obj->created_id                = $user->id;
                $obj->product_id                = $product_detail->id;
                $obj->exchange_date             = date("Y-m-d H:i:s");
                $obj->approved_date             = '0000-00-00 00:00:00';
                $obj->approved                  = 0;
                $obj->code                      = $vercode;
                $obj->point                     = $point_redeem;
                $obj->cash                      = $cash_redeem;
                $obj->point_id                  = $temp;
                $obj->status_of_redemption      = 1;
                $obj->status_of_redemption_date = date("Y-m-d H:i:s");
                $obj->pick_up_date              = '0000-00-00 00:00:00';
                $obj->pick_up_at                = $outlet;
                $obj->phone_num                 = '';
                $obj->quantity                  = $qty;
                $obj->type                      = 2;
                $db->insertObject('#__wrd_redemption', $obj); //update quality                
                $query = 'UPDATE #__wrd_products SET quantity = ' . ($product_detail->quantity - $qty) . ' WHERE id = ' . $product_detail->id;
                $db->setQuery($query);
                $db->query(); //send mail                
                $outlet = $_GET['res'];
                $mainframe->redirect('index.php?option=com_wrd&view=redemption&layout=finish&id=' . $post['pid'] . '&Itemid=127' . '&outlet=' . $outlet);
                return false;
            } else {
                $mainframe->redirect('index.php?option=com_wrd&view=redemption&layout=confirm', 'Need more point');
                return false;
            }
        }
    }
    
    function displayConfirm($tpl = null){

        $mainframe = JFactory::getApplication();
        $view = JRequest::getVar('view');
        $context = JRequest::getVar('option');

        $user = JFactory::getUser();
        if ($user->id != 0) {
            $model_profile = $this->getModel('profile');
            $model_product = $this->getModel('products');
            $user_info     = $model_profile->getUserProfile($user->id); //page title and point of user            
            $p_o_u         = WrdHelper::getPoints($user->id);
            $this->assignRef('p_o_u', $p_o_u);
            $p_title = WrdHelper::getPageTitle();
            $this->assignRef('p_title', $p_title); 
            // get products from parameter            
            
            $products = $_SESSION['form_convert'];
            if (products == null || products == "") {
                $mainframe->redirect(WrdHelperRoute::getProfileLoginRoute(), 'Your cart is empty');
                return;
            } // get products from parameter         
               
            $dummy = 0;
            foreach ($products as $product) {
                $props = explode(";", $product);
                if ($props['2'] != '0') {
                    $temp_proc                       = $model_product->getProductsConfirm($props['1']);
                    $product_details[$temp_proc->id] = $temp_proc;
                    $list_image[$temp_proc->id]      = $model_product->getListImages($props['1'], 1);
                    $methods[$temp_proc->id]         = $props['0'];
                    $qty[$temp_proc->id]             = $props['2'];
                    $dummy                           = $dummy + 1;
                }
            }
            
            $filter_pick_up_outlet = $mainframe->getUserStateFromRequest($context . $view . 'pick_up_at', 'pick_up_at', '', 'string');
            $o_let                 = JHTML::_('wrd.listOutletsEx2', 'pick_up_at', $states, '', 'pick_up_at', '', 'and cid = 01');

            //show list of products            
            $this->assignRef('methods', $methods);
            $this->assignRef('product_details', $product_details);
            $this->assignRef('list_image', $list_image);
            $this->assignRef('qty', $qty);
            $this->assignRef('outlets', $o_let);
        } else {
            $user_info = null;
            $mainframe->redirect(WrdHelperRoute::getProfileLoginRoute(), 'You must login first');
        }
        parent::display($tpl);
    }
    
    function displayCart($tpl = null)
    {
        $mainframe =& JFactory::getApplication();
        $user = JFactory::getUser();
        if ($user->id != 0) {
            $model_profile = $this->getModel('profile');
            $model_product = $this->getModel('products');
            $user_info     = $model_profile->getUserProfile($user->id); //page title and point of user           
            $p_o_u         = WrdHelper::getPoints($user->id);
            
            $this->assignRef('p_o_u', $p_o_u);
            $p_title = WrdHelper::getPageTitle();
            $this->assignRef('p_title', $p_title); // get products from parameter            
            $products = $_SESSION['form_convert']; // get products from parameter            
            $dummy    = 0;
            foreach ($products as $product) {
                $props = explode(";", $product);
                if ($props['2'] != '0') {
                    $temp_proc                       = $model_product->getProductsConfirm($props['1']);
                    $product_details[$temp_proc->id] = $temp_proc;
                    $list_image[$temp_proc->id]      = $model_product->getListImages($props['1'], 1);
                    $methods[$temp_proc->id]         = $props['0'];
                    $qty[$temp_proc->id]             = $props['2'];
                    $dummy                           = $dummy + 1;
                }
            } //show list of products            
            $this->assignRef('methods', $methods);
            $this->assignRef('product_details', $product_details);
            $this->assignRef('list_image', $list_image);
            $this->assignRef('qty', $qty);
        } else {
            $user_info = null;
            $mainframe->redirect(WrdHelperRoute::getProfileLoginRoute(), 'You must login first');
        }
        parent::display($tpl);
    }
    
    function displayEditCart($tpl = null)
    {
        $mainframe =& JFactory::getApplication();
        $user = JFactory::getUser();
        if ($user->id != 0) { // get products from parameter            
            $products                 = $_GET['product']; // save session           
            $_SESSION['form_convert'] = $products;
            $mainframe->redirect('index.php?option=com_wrd&view=redemption&layout=confirm');
        }
    }
    
    function displayFinish($tpl = null)
    {
        $mainframe =& JFactory::getApplication();
        $user = JFactory::getUser();
        $p_id = JRequest::getInt('id');
        $cat_id = JRequest::getInt('cat_id');
        
        if ($user->id != 0) {
            $model_profile = $this->getModel('profile');
            $user_info     = $model_profile->getUserProfile($user->id);
            
            if (!empty($p_id) && $p_id != 0) { 
            	//Lay chi tiet san pham co category id va product id da lay duoc                   
                $model_product   = $this->getModel('products');
                $category        = $model_product->getNameCat($cat_id);
                $product_details = $model_product->getProductsConfirm($p_id);
                $list_image      = array();
                $list_image      = $model_product->getListImages($product_details->id, 0);
            } //page title and point of user  

            $p_o_u = WrdHelper::getPoints($user->id);
            $this->assignRef('p_o_u', $p_o_u);
            $p_title = WrdHelper::getPageTitle();
            $this->assignRef('p_title', $p_title);
            $o_model        = JModelLegacy::getInstance('outlets', 'WrdModel');
            $o_let          = $o_model->getItem($_GET['outlet']);
            $confirm_number = $mainframe->getUserState('confirm_number');
            $this->assignRef('user_info', $user_info);
            $this->assignRef('user', $user);
            $this->assignRef('product_details', $product_details);
            $this->assignRef('outlet_name', $o_let->name);
            $this->assignRef('list_image', $list_image);
            $this->assignRef('confirm_number', $confirm_number);
            $mainframe->setUserState('confirm_number', '');
        } else {
            $user_info = null;
            $mainframe->redirect(WrdHelperRoute::getProfileLoginRoute(), 'You must login first');
        }
        parent::display($tpl);
    }
    
    function random_letters()
    {
        $mainframe = JFactory::getApplication();
        $sample    = array(
            'A',
            'B',
            'C',
            'D',
            'E',
            'F',
            'G',
            'H',
            'I',
            'J',
            'K',
            'L',
            'M',
            'N',
            'O',
            'P',
            'Q',
            'R',
            'S',
            'T',
            'U',
            'V',
            'W',
            'X',
            'Y',
            'Z'
        );
        $total     = count($sample);
        for ($i = 0; $i < 2; $i++) {
            $rand    = rand(0, $total - 1);
            $vercode = $vercode . $sample[$rand];
        }
        $vercode .= "" . rand(1000, 9999);
        return $vercode;
    }
}